package com.yiren.dbaa.module.practice_set.line.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.db.dao.controller.GradeDbController;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.currency.event.FragmentRefreshEvent;
import com.yiren.dbaa.currency.fragment.LazyLoadFragment;
import com.yiren.dbaa.module.project_edit.view.adapter.SelectParamAdapter;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.module.practice_set.line.contract.LineHomeContract;
import com.yiren.dbaa.module.practice_set.line.presenter.LineHomePresenter;
import com.yiren.dbaa.module.practice_set.line.view.activity.AddLineActivity;
import com.yiren.dbaa.module.practice_set.line.view.activity.LineEditActivity;
import com.yiren.dbaa.module.practice_set.line.view.activity.LineManageActivity;
import com.yiren.dbaa.module.practice_set.line.view.adapter.LineHomeAdapter;
import com.yiren.dbaa.util.DensityUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/10/12 13:38
 * @description: 线路数据fragment
 */
public class LineHomeFragment extends LazyLoadFragment implements LineHomeContract.View {

    @BindView(R.id.ll_site_name)
    LinearLayout llSiteName;
    @BindView(R.id.tv_current_site)
    TextView tvCurrentSite;
    @BindView(R.id.lv_line_data)
    ListView lvLineData;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.ll_add_line)
    LinearLayout llAddLine;

    private LineHomeContract.Presenter lineHomePresenter;
    private UserParamConfigBean userParamConfig;
    private List<LineInfoEntity> lineListSer;

    @Override
    protected int setContentView() {
        return R.layout.fragment_line_home;
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        userParamConfig = LoadConfigApi.loadUserParamConfig(getActivity());
        lineHomePresenter = new LineHomePresenter(getActivity());
        reFlush();
    }

    @Override
    public void onResume() {
        super.onResume();
        reFlush();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FragmentRefreshEvent event) {
        reFlush();
    }

    @OnClick({R.id.ll_add_line, R.id.ll_site_name})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_add_line:
                Intent intent = new Intent(getActivity(), AddLineActivity.class);
                intent.putExtra("lineListSer", (Serializable) lineListSer);
                startActivity(intent);
                break;
            case R.id.ll_site_name:
                showSelectDialog();
                break;
        }
    }

    private void reFlush() {
        userParamConfig = LoadConfigApi.loadUserParamConfig(getActivity());
        List<SiteEntity> localSites = UserDbController.getInstance(false).queryAll(SiteEntity.class);
        if (localSites.size() == 0) {
            userParamConfig.setSite(null);
            ParamConfigApi.saveUserParamConfig(getActivity(), userParamConfig);
        }
        if (userParamConfig.getSite() == null) {
            llNoData.setVisibility(View.VISIBLE);
            lvLineData.setVisibility(View.GONE);
            llSiteName.setVisibility(View.GONE);
            tvTips.setText("暂未选择考场，请先选择考场!");
            llAddLine.setVisibility(View.GONE);
        } else {
            DbConstant.GRADE_DATA_URL = DbConstant.App_Main_Directory + userParamConfig.getUserInfo().getId() + "/my/" + userParamConfig.getSite().getSiteCode() + "/" + DbConstant.GRADE_DATA_NAME;
            GradeDbController.getInstance(true);
            llSiteName.setVisibility(View.VISIBLE);
            llAddLine.setVisibility(View.VISIBLE);
            tvCurrentSite.setText("当前是" + userParamConfig.getSite().getSiteName() + "考规下的线路");
            lineHomePresenter.loadLineList(LineHomeFragment.this, userParamConfig.getSite().getSiteCode());
        }
    }

    @Override
    public void showLineList(List<LineInfoEntity> lineList) {
        lineListSer = lineList;
        if (lineList.size() == 0) {
            llNoData.setVisibility(View.VISIBLE);
            tvTips.setText("当前考规暂无线路，请先新增线路！");
            lvLineData.setVisibility(View.GONE);
        } else {
            llNoData.setVisibility(View.GONE);
            lvLineData.setVisibility(View.VISIBLE);
            LineHomeAdapter lineHomeAdapter = new LineHomeAdapter(getActivity(), lineList);
            lvLineData.setAdapter(lineHomeAdapter);

            //删除
            lineHomeAdapter.setOnDeleteClickListener(position -> {
                CommonDialog.showTwoBtn(getActivity(), "操作确认", "确定删除" + lineList.get(position).getName() + "吗？", "取消", "确认", (dialog, which) -> {
                    if (which == -2) {
                        dialog.dismiss();
                    } else {
                        lineHomePresenter.deleteLine(lineList.get(position), new CommonCallBack() {
                            @Override
                            public void success(Object result) {
                                reFlush();
                                dialog.dismiss();
                            }
                        });
                    }
                });
            });

            //管理下载编辑规则
            lineHomeAdapter.setOnManageClickListener(position -> {
                if (userParamConfig.isPartner()) {
                    if (lineList.get(position).isDownLoad()) {
                        //管理页
                        Intent intent = new Intent(getActivity(), LineManageActivity.class);
                        intent.putExtra("line", lineList.get(position));
                        startActivity(intent);
                    } else {
                        //下载
                        lineHomePresenter.downLoadLineData(lineList.get(position), LineHomeFragment.this);
                    }
                } else {
                    if (lineList.get(position).isDownLoad()) {
                        //编辑
                        Intent intent = new Intent(getActivity(), LineEditActivity.class);
                        intent.putExtra("line", lineList.get(position));
                        intent.putExtra("pageType", 2);
                        startActivity(intent);
                    } else {
                        //下载
                        lineHomePresenter.downLoadLineData(lineList.get(position), LineHomeFragment.this);
                    }
                }
            });
        }
    }

    @Override
    public void refreshLineList() {
        lineHomePresenter.loadLineList(this, userParamConfig.getSite().getSiteCode());
    }

    /**
     * 显示切换考规对话框
     */
    public void showSelectDialog() {
        String selectString = "";
        if (userParamConfig.getSite() != null)
            selectString = userParamConfig.getSite().getSiteName();
        List<SiteEntity> siteList = UserDbController.getInstance(false).queryAll(SiteEntity.class);
        List<String> selectList = new ArrayList<>();
        for (SiteEntity site : siteList) {
            selectList.add(site.getSiteName());
        }
        Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(getContext()) * 7) / 10;
        params.height = (DensityUtil.getScreenHeight(getContext()) * 6) / 10;
        dialog.getWindow().setAttributes(params);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_select_box);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        ListView lvList = (ListView) window.findViewById(R.id.lv_dialog_list);
        lvList.setDivider(null);// 去除listview的下划线
        tvTitle.setText("请选择考场");
        SelectParamAdapter adapter = new SelectParamAdapter(getActivity(), selectList, selectString);
        lvList.setAdapter(adapter);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvCurrentSite.setText("当前是" + selectList.get(position) + "考规下的线路");
                userParamConfig.setSite(siteList.get(position));
                ParamConfigApi.saveUserParamConfig(getActivity(), userParamConfig);
                DbConstant.GRADE_DATA_URL = DbConstant.App_Main_Directory + userParamConfig.getUserInfo().getId() + "/my/" + userParamConfig.getSite().getSiteCode() + "/" + DbConstant.GRADE_DATA_NAME;
                GradeDbController.getInstance(true);
                refreshLineList();
                dialog.dismiss();
            }
        });
    }
}
